<script setup>
import { DraggableModal } from '@/components/core/draggable-modal'
import { ref, onMounted, reactive, nextTick, unref } from 'vue'
import { queryCustomersList, queryNotePageList } from '@/api/home'
import YearPopover from '@/components/PersonalInfo/YearPopover.vue'
import AddRemarkModal from './AddRemarkModal.vue'

import { queryPolicyInfo } from '@/api/comprehensive'
import { formatColumn } from '@/utils/tools.js'
import cloneDeep from 'lodash/cloneDeep'
import dayjs from 'dayjs' // 用于处理日期

const props = defineProps({
  insuredInfo: {
    type: Object,
    required: () => {}
  },
  policyInfo: {
    type: Object,
    required: () => {}
  },
  showSearchPageLink: {
    // 弹框是否展示返回综合查询link
    type: Boolean,
    default: true
  }
})
const emit = defineEmits(['updateVisible'])
const dateFormat = 'YYYY-MM-DD'

const policyInfos = ref(props.policyInfo)
const today = dayjs() // 获取当前日期
const threeYearsAgo = dayjs().subtract(3, 'year') // 当前日期向前推三年
const dataSource = ref([])
const formData = ref({
  memberId: props?.insuredInfo?.memberId || props?.insuredInfo?.member_id, //会员号
  customId: props?.insuredInfo?.customerId || props?.insuredInfo?.customer_id, //用户姓名
  planTypeEName: policyInfos.value.planTypeEName, //计划类型
  insuredEffectiveDate: policyInfos.value.insuredEffectiveDate, //被保人有效期开始
  insuredExpireDate: policyInfos.value.insuredExpireDate, // 被保人有效期结束
  noteContent: '', // 备注
  modifyDate: [threeYearsAgo, today] // 操作区间
})
const pagination = reactive({
  current: 1,
  pageSize: 10,
  size: 'large',
  showSizeChanger: true,
  total: 0,
  onChange: handlePageChange
})
function handlePageChange(page, pageSize) {
  pagination.current = page
  pagination.pageSize = pageSize
  search()
}
let loading = ref(false)
let searchFromData = ref(cloneDeep(formData.value))
function searchForm() {
  pagination.current = 1
  searchFromData.value = cloneDeep(formData.value)
  search()
}
async function search() {
  loading.value = true
  let operationStartDate = ''
  if (searchFromData.value?.modifyDate && searchFromData.value?.modifyDate[0]) {
    operationStartDate = dayjs(searchFromData.value?.modifyDate[0]).format('YYYY-MM-DD')
  }
  let operationEndDate = ''
  if (searchFromData.value?.modifyDate && searchFromData.value?.modifyDate[1]) {
    operationEndDate = dayjs(searchFromData.value?.modifyDate[1]).format('YYYY-MM-DD')
  }

  let params = {
    model: {
      ...searchFromData.value,
      operationStartDate: operationStartDate,
      operationEndDate: operationEndDate
    },
    current: pagination.current,
    size: pagination.pageSize
  }
  console.log('params', params)
  let res = null
  try {
    res = await queryNotePageList(params)
  } catch (err) {
    console.log('err', err)
  } finally {
    loading.value = false
  }
  if (!res.isSuccess) return
  pagination.total = Number(res.data.total)
  dataSource.value = res?.data?.records || []
}

const remarkVisible = ref(false)
async function initData() {
  pagination.current = 1
}
onMounted(async () => {
  await nextTick()
  remarkVisible.value = true
  getInsuredList()
  initData()
  fetchPolicyInfo('init')
})
const remarkColumns = [
  {
    title: '序号',
    width: 70,
    dataIndex: 'Index',
    customRender: ({ text, record, index }) => `${index + 1}`
  },
  {
    title: '备注类型',
    dataIndex: 'noteType',
    key: 'noteType',
    width: 120,
    customRender: ({ text, record, index }) => formatColumn(text)
  },
  {
    title: '备注子类型',
    dataIndex: 'insuredNoteSubType',
    key: 'insuredNoteSubType',
    width: 120,
    customRender: ({ text, record, index }) => formatColumn(text)
  },
  {
    title: '备注内容',
    dataIndex: 'noteContent',
    key: 'noteContent',
    width: 160,
    customRender: ({ text, record, index }) => formatColumn(text)
  },
  {
    title: '操作人',
    dataIndex: 'operator',
    key: 'operator',
    width: 120,
    customRender: ({ text, record, index }) => formatColumn(text)
  },
  {
    title: '操作日期',
    dataIndex: 'modifyDate',
    key: 'modifyDate',
    width: 120,
    customRender: ({ text, record, index }) => formatColumn(text)
  },
  {
    title: '操作时间',
    dataIndex: 'modifyTime',
    key: 'modifyTime',
    width: 120,
    customRender: ({ text, record, index }) => formatColumn(text)
  }
]
function reset() {
  formData.value.noteContent = ''
  formData.value.modifyDate = []
}
function updateCustomInfoFun(selectYearInfo) {
  policyInfos.value = selectYearInfo
  formData.value.planTypeEName = policyInfos.value.planTypeEName //计划类型
  formData.value.insuredEffectiveDate = policyInfos.value.insuredEffectiveDate //计划类型
  formData.value.insuredExpireDate = policyInfos.value.insuredExpireDate //计划类型
  formData.value.memberId = policyInfos.value.member_id
  formData.value.customId = policyInfos.value.customer_id
  dataSource.value = []
}

function handleCancel() {
  remarkVisible.value = false
  emit('updateVisible', false)
}
// 每次切换被保人，保单年度都会重新取值，取当前被保人返回的保单年度列表的第一个作为初始值

function changeCustomerId() {
  fetchPolicyInfo('changeDocId')
  dataSource.value = []
}
function getDoctId(type) {
  let doc_id = null
  if (type == 'init') {
    doc_id = unref(props.insuredInfo).doc_id
  } else {
    doc_id = unref(insuredList).find((item) => item.customerId == unref(formData).customId)?.doc_id
  }
  return doc_id
}
const policyList = ref([])
async function fetchPolicyInfo(type) {
  const doc_id = getDoctId(type)
  let res = null
  const data = {
    desensitization: '02',
    doc_id
  }
  try {
    res = await queryPolicyInfo(data)
  } catch (err) {
    console.log('err', err)
  }
  if (res?.isSuccess) {
    policyList.value = res?.data || []
    if (type == 'changeDocId') {
      policyInfos.value = unref(policyList)[0]
    }
  }
}

// 获取客户列表
const insuredList = ref([])
async function getInsuredList(type) {
  let res = null
  try {
    const data = {
      desensitization: '02',
      insuredId: policyInfos.value.insuredId
    }
    res = await queryCustomersList(data)
  } catch (err) {
    console.log('err', err)
  }
  if (res?.isSuccess) {
    insuredList.value = res.data
  }
}
// 新增备注
const addRemarkVisible = ref(false)
function addRemark() {
  addRemarkVisible.value = true
}
</script>
<template>
  <DraggableModal
    :showCloseIcon="true"
    :showSearchPageLink="showSearchPageLink"
    :footer="null"
    @cancel="handleCancel"
    v-model:open="remarkVisible"
    width="1230px"
    title="备注信息"
  >
    <div class="remark-main-header">
      <a-row :gutter="[16, 20]">
        <a-col class="gutter-row" :span="6">
          <p class="title">会员ID</p>
          <a-input v-model:value="formData.memberId" disabled />
        </a-col>
        <a-col class="gutter-row" :span="6">
          <p class="title">客户姓名</p>
          <a-select
            v-model:value="formData.customId"
            optionFilterProp="customerId"
            style="width: 100%"
            :field-names="{ label: 'name', value: 'customerId' }"
            :options="insuredList"
            @change="changeCustomerId"
          >
          </a-select>
        </a-col>
        <a-col class="gutter-row" :span="6">
          <p class="title">保单年度</p>
          <YearPopover
            @updateCustomInfo="updateCustomInfoFun"
            :info="policyInfos"
            :policyYearList="policyList"
            :requireGetYearList="false"
          >
            <div class="policy-year-box cursor-pointer mr-20">
              <span class="policy-year">
                {{ policyInfos.policyYear }}
              </span>
              <svg-icon class="arrow-year-icon" size="14" name="arrow-down" />
            </div>
          </YearPopover>
        </a-col>
        <a-col class="gutter-row" :span="6">
          <p class="title">计划类型</p>
          <a-input disabled :value="policyInfos.planTypeEName" placeholder="计划类型" allow-clear />
        </a-col>
        <a-col class="gutter-row" :span="6">
          <p class="title">被保人有效期</p>
          <a-input
            class="mr-20"
            :value="`${policyInfos.insuredEffectiveDate} ~ ${policyInfos.insuredExpireDate}`"
            placeholder="有效期"
            disabled
          />
        </a-col>
        <a-col class="gutter-row" :span="6">
          <p class="title">备注</p>
          <a-input v-model:value="formData.noteContent" />
        </a-col>
        <a-col class="gutter-row" :span="6">
          <p class="title">操作日期</p>
          <a-range-picker v-model:value="formData.modifyDate" :format="dateFormat" />
        </a-col>
        <a-col class="gutter-search" :span="6">
          <a-button type="primary" class="search-btn" @click="searchForm">{{
            $t('global.search')
          }}</a-button>
          <a-button @click="reset" class="search-btn">{{ $t('global.reset') }}</a-button>
        </a-col>
      </a-row>
    </div>
    <div class="remark-main-center">
      <a-button type="primary" @click="addRemark" class="search-btn">新增</a-button>
    </div>
    <a-table
      class="ant-table-sub-striped"
      :columns="remarkColumns"
      :scroll="{ y: 350 }"
      :loading="loading"
      :data-source="dataSource"
      :pagination="pagination"
    >
    </a-table>
  </DraggableModal>
  <Teleport to="body">
    <AddRemarkModal
      :showSearchPageLink="showSearchPageLink"
      :insuredId="props.policyInfo.insuredId"
      v-if="addRemarkVisible"
      @updateVisible="(visible) => (addRemarkVisible = visible)"
      @updateRemarkList="search"
    ></AddRemarkModal>
  </Teleport>
</template>
<style lang="scss">
.remark-main-header {
  margin-bottom: 20px;
  .ant-input-affix-wrapper {
    box-sizing: border-box;
    padding-left: 15px;
    height: 32px;
    border-radius: 4px;
    border: 1px solid #dfdfdf;
  }
  .search-btn {
    margin-right: 16px;
  }
  .gutter-row {
    p {
      margin-bottom: 10px;
    }
    .search-icon {
      width: 100%;
      height: 100%;
      background: #729db0;
    }
  }
  .gutter-search {
    padding-top: 32px;
    display: flex;
    align-items: center;
  }
  .policy-year-box {
    width: 100%;
    height: 32px;
    display: flex;
    border-radius: 6px;
    background-color: #ffffff;
    border: 1px solid #d9d9d9;
    align-items: center;
    position: relative;
    justify-content: space-between;
    padding: 0 11px;
    .policy-year {
      font-size: 14px;
      color: #333333;
    }
    .arrow-year-icon {
      color: #ccc;
    }
  }
}
.remark-main-center {
  margin-top: 20px;
  display: flex;
  justify-content: end;
  margin-bottom: 16px;
}
</style>
